<script setup>
/**
 * @description 餐厅预约订单管理组件
 * 功能包括：订单查询、预约信息查看、订单状态更新、分页展示等
 */
// 导入所需的Vue组件和工具
import { ref, reactive, onMounted, watch,toRaw  } from 'vue'
import axios from 'axios'

// 筛选表单
const orderType = ref("餐桌预约");
const filterForm = reactive({
  orderNumber: '',
  storeName: '', // 绑定到下拉框的选中值
  orderStatus: '', // 绑定到下拉框的选中值
  orderType: orderType.value,
  orderTime: '',
  endTime: ''
});
//导出订单数据到Excel文件
const exportToExcel = (tableData) => {
  document.location.href = "`http://localhost:8080/indent/download`";
};
// 分页配置信息
const pagination = reactive({
  pageNum: 1,      // 当前页码
  pageSize: 10,    // 每页显示条数
  total: 100       // 总记录数
})

// 表格数据列表
const tableData = ref([])

/**
 * 综合查询方法
 * 重置分页信息并执行筛选查询
 */
const handleQuery = () => {
  pagination.pageNum = 1;
  pagination.pageSize = 10;
  fetchDataWithFilter();
};
const fetchDataWithFilter = () => {
  const { orderNumber, storeName, orderType, orderTime, endTime } = filterForm;
  const params = {
    orderNumber,    // 订单编号
    storeName,      // 门店名称
    orderType,      // 订单类型
    orderTime,      // 下单时间
    endTime,        // 结束时间
    pageNum: pagination.pageNum,
    pageSize: pagination.pageSize
  };
  axios.post(`/indent/select/${pagination.pageNum}/${pagination.pageSize}`, params).then((res) => {
    tableData.value = res.data.data;
    pagination.total = res.data.total;
  });
};

/**
 * 处理每页显示条数变化
 * @param {number} val - 新的每页显示条数
 */
const handleSizeChange = (val) => {
  pagination.pageSize = val
}
/**
 * 处理当前页码变化
 * @param {number} val - 新的页码
 */
const handleCurrentChange = (val) => {
  pagination.pageNum = val
}
// 订单状态和门店名称下拉框数据
const OrderStatus111 = ref([]); // 订单状态列表
const StoreName111 = ref([]);   // 门店名称列表

/**
 * 获取订单状态下拉框数据
 */
const feData1 = () => {
  axios.get("/indent/allOrderStatus").then((res) => {
    OrderStatus111.value = res.data;
  });
};

/**
 * 获取门店名称下拉框数据
 */
const feData2 = () => {
  axios.get("/indent/allStoreName").then((res) => {
    StoreName111.value = res.data;
  });
};
//获取订单列表数据
const fetchData = () => {
  axios.get(`/indent/allReceipt/${orderType.value}/${pagination.pageNum}/${pagination.pageSize}`).then((res) => {
    tableData.value = res.data.data;
    pagination.total = res.data.total;
  });
};
// 控制预约信息弹窗的显示状态
const dialogVisible = ref(false)

// 预约表单数据结构
const formData = ref({
    id: null,
    title: '',
    storeName: '',
    storeAddress: '',
    storePhone: '',
    cashier: '',
    deliveryPerson: null,
    deliveryPhone: null,
    orderNumber: '',
    orderType: '',
    orderStatus: '',
    customerName: '',
    customerPhone: '',
    takeoutUsername: null,
    takeoutPhone: null,
    deliveryAddress: null,
    tableNumber: '',
    orderTime: '',
    reservationTime: '',
    reservationPeople: null,
    contactName: '',
    bookedBy: '',
    dishId: '',
    dishInfo: '',
    totalAmount: 0,
    packingFee: 0,
    deliveryFee: 0,
    discountAmount: 0,
    actualAmount: 0,
    paymentMethod: '',
    paymentTime: '',
    remark: '',
    printTime: ''
})
//
const handleShowDialog = (index,row) => {
  axios.get(`/indent/${row.id}`).then((res) => {
    formData.value= res.data.receipt;
  });
  dialogVisible.value = true;
}
const handleConfirm = async () => {
  formData.value.orderStatus = "已确认";
  const payload = toRaw(formData.value); // 获取原始对象
  axios.post('/indent/updateStatus', payload).then((res) => {
    // 处理响应
  });
  dialogVisible.value = false;
};

const handleCancel = async () => {
  formData.value.orderStatus = "已取消";
  const payload = toRaw(formData.value); // 获取原始对象
  axios.post('/indent/updateStatus', payload).then(() => {
    // 处理响应
  });
  dialogVisible.value = false;
};

const handleDelete = async (index,row) => {
  try {
    await axios.delete(`/indent/delete/${row.id}`)
    dialogVisible.value = false;
  } catch (error) {
    console.error('删除订单失败:', error)
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  fetchData()  // 获取订单列表
  feData1()    // 获取订单状态选项
  feData2()    // 获取门店名称选项
})

// 监听分页参数变化，自动刷新数据
watch(
    () => [pagination.pageNum, pagination.pageSize],
    ([newPageNum, newPageSize]) => {
      fetchData();
    }
);
</script>

<template>
  <div class="dine-in-order-container">
    <!-- 顶部标题 -->
    <div class="header">
      <h1>预约订单</h1>
    </div>
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="订单编号">
          <el-input v-model="filterForm.orderNumber" placeholder="请输入" clearable/>
        </el-form-item>
        <el-form-item label="请选择门店">
          <el-select v-model="filterForm.storeName" placeholder="请选择">
            <el-option
                v-for="status in StoreName111"
                :key="status"
                :label="status"
                :value="status">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请选择订单状态">
          <el-select v-model="filterForm.orderStatus"  placeholder="请选择">
            <el-option
                v-for="status in OrderStatus111"
                :key="status"
                :label="status"
                :value="status">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
              v-model="filterForm.orderTime"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="fetchData">刷新</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <div class="table-container">
      <el-button type="text" size="small" @click="exportToExcel">导出</el-button>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="订单id" width="180" />
        <el-table-column prop="orderNumber" label="订单编号" width="150" />
        <el-table-column prop="orderTime" label="提交时间" width="150" />
        <el-table-column prop="reservationTime" label="预约时间" width="150" />
        <el-table-column prop="storeName" label="所属门店" width="150" />
        <el-table-column prop="reservationPeople" label="就餐人数" width="120" />
        <el-table-column prop="tableNumber" label="桌号" width="120" />
        <el-table-column prop="contactName" label="联系人" width="120" />
        <el-table-column prop="customerPhone" label="手机号" width="120" />
        <el-table-column prop="bookedBy" label="预订员工" width="120" />
        <el-table-column prop="orderStatus" label="订单状态" width="120">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleShowDialog(scope.$index, scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--    分页-->
    <div class="block">
      <span class="demonstration">调整每页显示条数</span>
      <el-pagination
          :page-sizes="[1, 3, 5,10,15,20,50]"
          :total="pagination.total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          layout="total,sizes, prev, pager, next"
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize">
      </el-pagination>
    </div>
  </div>
  <!-- 预约信息弹窗 -->
  <div>
    <el-dialog
        title="预约信息"
        v-model="dialogVisible"
        width="30%"
        :close-on-click-modal="false"
    >
      <el-form :model="formData" label-width="100px">
        <el-form-item label="联系人" >
          <el-input v-model="formData.contactName"  />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="formData.customerPhone"  />
        </el-form-item>
        <el-form-item label="门店">
          <el-input v-model="formData.storeName"   />
        </el-form-item>
        <el-form-item label="预约时间">
          <el-input v-model="formData.reservationTime"   />
        </el-form-item>
        <el-form-item label="就餐人数">
          <el-input v-model="formData.reservationPeople"   />
        </el-form-item>
        <el-form-item label="桌号">
          <el-input v-model="formData.tableNumber"  />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
        <el-button type="danger" @click="handleCancel">取消订单</el-button>
      </span>
      </template>
    </el-dialog>
  </div>

</template>
<style scoped>

.dine-in-order-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  margin-bottom: 20px;
}

.header h1 {
  font-size: 20px;
  color: #333;
  margin: 0;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}
</style>